package com.gcloud.googledrive;


import java.io.IOException;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import com.google.api.services.drive.model.File;
import com.dropbox.client2.DropboxAPI;
import com.dropbox.client2.android.AndroidAuthSession;
import com.example.gcode.Archivos;
import com.example.gcode.GCloudSingleton;
import com.example.gcode.R;
import com.gfilechooser.utils.FileUtils;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;
import com.google.api.client.http.FileContent;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.Drive.Files;
import com.google.api.services.drive.model.FileList;
import com.utils.GCloudUtil;

import android.accounts.AccountManager;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

public class UploadGoogleFileActivity extends Activity {
	
	private ProgressDialog pDialog;
	
	public static Drive service;
	GoogleAccountCredential credential;
	private static final int REQUEST_ACCOUNT = 1;
	private static final int REQUEST_CODE = 100;

	/* DROP BOX THINGS */

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.archivos_list);
		
		credential = GoogleAccountCredential.usingOAuth2(
				UploadGoogleFileActivity.this, DriveScopes.DRIVE);
		startActivityForResult(credential.newChooseAccountIntent(),
				REQUEST_ACCOUNT);
	}


	private void showChooser() {
		// Use the GET_CONTENT intent from the utility class
		Intent target = FileUtils.createGetContentIntent();
		// Create the chooser Intent
		Intent intent = Intent.createChooser(target,
				getString(R.string.chooser_title));
		try {
			startActivityForResult(intent, REQUEST_CODE);
		} catch (ActivityNotFoundException e) {
			// The reason for the existence of aFileChooser
		}
	}

	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Log.i("jalskjdf", "guaro!!");
		switch (item.getItemId()) {
		case R.id.menu_upload:

			Log.i("here", "upload");
			showChooser();
			break;
		case R.id.menu_download:
			Log.i("here", "download");
			break;
		case R.id.menu_delete:
			Log.i("here", "delete");
			break;
		case R.id.menu_bookmark:
			Log.i("here", "bookmark");
			break;
		case R.id.menu_save:
			Log.i("here", "save");
			break;
		case R.id.menu_search:
			Log.i("here", "search");
			break;
		case R.id.menu_google_drive:
			Log.i("here", "google drive");
			break;
		case R.id.menu_dropbox:
			Log.i("here", "dropbox");
			break;
		}
		return true;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.layout.menu_layout, menu);
		return true;
	}

	

	

	

	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case REQUEST_ACCOUNT:
			if (resultCode == RESULT_OK && data != null
					&& data.getExtras() != null) {
				String accountName = data
						.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
				 credential.setSelectedAccountName(accountName);
				 UploadGoogleFileActivity.service = getDriveServices(credential);
				 showChooser();
				Log.i("GCLOUD", "Ya entre a doInBackground :)");
//				ListGoogleFile listGoogle = new ListGoogleFile(service,
//						getApplicationContext());
				Log.i("OnActivitty", "before to execute");
//				try {
//					listGoogle.execute();
//					showFilesOnUi();
//				} catch (Exception e) {
//					Log.i("Exception catch", e.toString());
//					// startActivityForResult(credential.newChooseAccountIntent(),
//					// REQUEST_CONFIRMATION);
//				}
				Log.i("OnActivitty", "after execute");

			}
			break;
		case REQUEST_CODE:
			if (resultCode == RESULT_OK) {
				if (data != null) {
					// Get the URI of the selected file
					final Uri uri = data.getData();
					try {
						// Create a file instance from the URI
						final java.io.File file = FileUtils.getFile(uri);
						showToast("File selected: " + file.getAbsolutePath());
//						UploadGoogleFile uploadFile=new UploadGoogleFile(UploadGoogleFileActivity.service, UploadGoogleFileActivity.this, file);
//						uploadFile.execute();
						CargarArchivos uploadGoogleFile=new CargarArchivos();
							uploadGoogleFile.setFile(uri,UploadGoogleFileActivity.service);
						uploadGoogleFile.execute();
					} catch (Exception e) {
						Log.e("FileSelectorTestActivity", "File select error",
								e);
					}
				}
			}
			break;
		}
	}

	

	private Drive getDriveServices(GoogleAccountCredential credential) {
		return new Drive.Builder(AndroidHttp.newCompatibleTransport(),
				new GsonFactory(), credential).build();
	}

	public void showToast(final String toast) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				Toast.makeText(getApplicationContext(), toast,
						Toast.LENGTH_SHORT).show();
			}
		});
	}

	
	
	

	
	

	class CargarArchivos extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(UploadGoogleFileActivity.this);
//			pDialog.setMessage("Uploading file to Google Drive ...");
//			pDialog.setIndeterminate(false);
//			pDialog.setCancelable(false);
//			pDialog.show();
		}
		
		
		Uri uri;
		GCloudSingleton gCloudSingleton;
		String answer="false";
		Drive gService;
		
		
		protected void setFile(Uri  file, Drive service){
		
			uri=file;
			this.gService=service;
		}
		
		
		/**
		 * getting Inbox JSON
		 * */
		protected String doInBackground(String... voids) {

			Log.i("GCLOUD", "Ya entre a doInBackground :)");

			Thread t = new Thread(new Runnable() {
				@Override
				public void run() {
					try {

						java.io.File fileContent =// regularFile;
						new java.io.File(uri.getPath());
						String mimeType = GCloudUtil.getMimeTypeFromURI(uri.getPath());
						Log.i(" inside thread: "," Data: "+fileContent.getAbsolutePath()+ " :: "+mimeType);
						FileContent mediaContent = new FileContent(mimeType,
								fileContent);
						File body = new File();
						body.setTitle(fileContent.getName());
						body.setMimeType(mimeType);
						
						File file = UploadGoogleFileActivity.service.files().insert(body, mediaContent)
								.execute();
						if (file != null) {
							//showToast("File uploaded: " + file.getTitle());
							Log.i("UploadGoogleFile", "File uploaded");
							answer="true";
						}
						
					} catch (UserRecoverableAuthIOException e) {
						Log.i("UploadGoogleFile", "account user not authorized: " + e);
						answer+=e.getLocalizedMessage();
//						 startActivityForResult(e.getIntent(),
//						 REQUEST_AUTHORIZATION);
						return;
					} catch (IOException e) {
						Log.i("UploadGoogleFile", "IOException: " + e);
						answer+=e.getLocalizedMessage();
						return;
					}
				}
			});
			t.start();
			return answer;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			if(file_url.equalsIgnoreCase("true")){
			showToast("everything well done");
			Intent newIntent=new Intent(UploadGoogleFileActivity.this, Archivos.class);
			startActivity(newIntent);
			}else{
				showToast(answer);	
			}
			
			// if(){
//			 startActivityForResult(credential.newChooseAccountIntent(),
//			 REQUEST_ACCOUNT);
			// }
			// updating UI from Background Thread			
		}

	}
}